<?php namespace App\Http\Controllers\V1;

use App\Http\Controllers\Controller;
use App\Models\Member;
use Illuminate\Support\Facades\Validator;

class MemberController extends Controller
{
	public function index()
	{
		$items = Member::query()
//			->where('device_id', $this->user->device_id)
			->when($this->word, function ($query) {
				return $query->where('name', 'like', '%' . $this->word . '%')
					->orWhere('mobile', 'like', '%' . $this->word . '%');
			})
			->orderBy('id')
			->paginate($this->per_page);
		return $this->items($items);
	}

	public function create()
	{
		$input = $this->request->only('avatar', 'name', 'mobile', 'birthday', 'sex');
		$vdt   = Validator::make($input, Member::rules(), Member::messages());
		if ($vdt->fails()) {
			return $this->failed($vdt->errors()->first());
		}
//		$input['device_id'] = $this->user->device_id;
		Member::query()->create($input);
		return $this->success();
	}

	public function update($id)
	{
		$mbr = Member::query()->find($id);
		if (is_null($mbr)) {
			return $this->failed('成员不存在');
		}
		$input = $this->request->only('avatar', 'name', 'mobile', 'birthday', 'sex');
		$vdt   = Validator::make($input, Member::rules(), Member::messages());
		if ($vdt->fails()) {
			return $this->failed($vdt->errors()->first());
		}
		$mbr->fill($input)->save();
		return $this->success();
	}

	public function drop($id)
	{
		$mbr = Member::query()->find($id);
		if (is_null($mbr)) {
			return $this->failed('成员不存在');
		}
		$mbr->delete();
		return $this->success();
	}
}
